import React, { createContext, useContext, useEffect, ReactNode, useState, useCallback } from 'react';
import { Order, Statistics } from '../types';
import { webSocketService, WebSocketCallbacks } from '../services/websocket';
import { useAuth } from './useAuth';

interface RealtimeContextType {
  isConnected: boolean;
  connectionState: number;
  onOrderUpdate: (callback: (order: Order) => void) => void;
  onStatisticsUpdate: (callback: (statistics: Statistics) => void) => void;
  removeOrderUpdateListener: (callback: (order: Order) => void) => void;
  removeStatisticsUpdateListener: (callback: (statistics: Statistics) => void) => void;
}

const RealtimeContext = createContext<RealtimeContextType | undefined>(undefined);

interface RealtimeProviderProps {
  children: ReactNode;
}

export const RealtimeProvider: React.FC<RealtimeProviderProps> = ({ children }) => {
  const { isAuthenticated, user } = useAuth();
  const [isConnected, setIsConnected] = useState(false);
  const [connectionState, setConnectionState] = useState(WebSocket.CLOSED);
  const [orderUpdateCallbacks] = useState<Set<(order: Order) => void>>(new Set());
  const [statisticsUpdateCallbacks] = useState<Set<(statistics: Statistics) => void>>(new Set());

  // WebSocket回调 - 使用useCallback稳定化
  const callbacks: WebSocketCallbacks = React.useMemo(() => ({
    onConnect: () => {
      setIsConnected(true);
      setConnectionState(WebSocket.OPEN);
      console.log('实时连接已建立');
    },
    onDisconnect: () => {
      setIsConnected(false);
      setConnectionState(WebSocket.CLOSED);
      console.log('实时连接已断开');
    },
    onError: (error) => {
      console.error('实时连接错误:', error);
      setIsConnected(false);
    },
    onOrderCreated: (order: Order) => {
      console.log('新工单创建:', order);
      orderUpdateCallbacks.forEach(callback => callback(order));
    },
    onOrderUpdated: (order: Order) => {
      console.log('工单更新:', order);
      orderUpdateCallbacks.forEach(callback => callback(order));
    },
    onOrderAssigned: (order: Order) => {
      console.log('工单分配:', order);
      orderUpdateCallbacks.forEach(callback => callback(order));
    },
    onOrderCompleted: (order: Order) => {
      console.log('工单完成:', order);
      orderUpdateCallbacks.forEach(callback => callback(order));
    },
    onStatisticsUpdated: (statistics: Statistics) => {
      console.log('统计数据更新:', statistics);
      statisticsUpdateCallbacks.forEach(callback => callback(statistics));
    },
  }), [orderUpdateCallbacks, statisticsUpdateCallbacks]);

  // 建立连接
  useEffect(() => {
    if (isAuthenticated && user?.role === 'admin') {
      console.log('建立实时数据连接...');
      webSocketService.connect(callbacks);
      
      // 更新token
      const token = localStorage.getItem('admin_token');
      if (token) {
        webSocketService.updateToken(token);
      }
    } else {
      webSocketService.disconnect();
      setIsConnected(false);
      setConnectionState(WebSocket.CLOSED);
    }

    return () => {
      webSocketService.disconnect();
    };
  }, [isAuthenticated, user, callbacks]);

  // 监听连接状态变化
  useEffect(() => {
    const interval = setInterval(() => {
      const state = webSocketService.getConnectionState();
      setConnectionState(state);
      setIsConnected(state === WebSocket.OPEN);
    }, 1000);

    return () => clearInterval(interval);
  }, []);

  const onOrderUpdate = useCallback((callback: (order: Order) => void) => {
    orderUpdateCallbacks.add(callback);
  }, [orderUpdateCallbacks]);

  const onStatisticsUpdate = useCallback((callback: (statistics: Statistics) => void) => {
    statisticsUpdateCallbacks.add(callback);
  }, [statisticsUpdateCallbacks]);

  const removeOrderUpdateListener = useCallback((callback: (order: Order) => void) => {
    orderUpdateCallbacks.delete(callback);
  }, [orderUpdateCallbacks]);

  const removeStatisticsUpdateListener = useCallback((callback: (statistics: Statistics) => void) => {
    statisticsUpdateCallbacks.delete(callback);
  }, [statisticsUpdateCallbacks]);

  const value = {
    isConnected,
    connectionState,
    onOrderUpdate,
    onStatisticsUpdate,
    removeOrderUpdateListener,
    removeStatisticsUpdateListener,
  };

  return <RealtimeContext.Provider value={value}>{children}</RealtimeContext.Provider>;
};

export const useRealtime = () => {
  const context = useContext(RealtimeContext);
  if (context === undefined) {
    throw new Error('useRealtime must be used within a RealtimeProvider');
  }
  return context;
};